#include "setwig.h"
#include "ui_setwig.h"

QJsonObject  json;

SetWig::SetWig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SetWig)
{
    ui->setupUi(this);
    pr=new recognition(this);

    udpSocket = new QUdpSocket(this);
    tcpSocket1 =  new QTcpSocket(this);
    tcpSocket2 =  new QTcpSocket(this);

    timer = new QTimer(this);

    connect(ui->pushButtonSearch,SIGNAL(clicked()),this,SLOT(btnSearchSlot()));
    connect(udpSocket,SIGNAL(readyRead()),this,SLOT(udpRecvSlot()));
    connect(ui->pushButtonConnect,SIGNAL(clicked()),
            this,SLOT(btnConnectSolt()));
    connect(tcpSocket1,SIGNAL(readyRead()),this,SLOT(tcpSecondConnectSlot()));
    connect(tcpSocket2,SIGNAL(connected()),this,SLOT(tcpSendFileSlot()));
    connect(this,SIGNAL(disconnectTcpSignal()),this,SLOT(disconnectedSlot()));

    connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(btnpatternSlot())); //更改模式槽函数
    connect(ui->pushButton_2,SIGNAL(clicked()),pr,SLOT(show()));//弹窗人脸识别
    connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(openFun()));

    timer->setSingleShot(false);
    timer->setInterval(10000);
    connect(timer,SIGNAL(timeout()),SLOT(timeoutHeartSlot()));
    timer->start();
    
}

void SetWig::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    QPixmap pic(":/new/prefix1/login.jpg");
    painter.drawPixmap(0,0,this->width(),this->height(),pic);
}



SetWig::~SetWig()
{
    if(tcpSocket1->isOpen())
        tcpSocket1->close();
    if(tcpSocket2->isOpen())
        tcpSocket2->close();
    if(udpSocket->isOpen())
        udpSocket->close();
        timer->stop();
    delete ui;
    delete timer;
}

void SetWig::btnSearchSlot()
{
    QHostAddress broadcastAddress(UDPIP);

    QByteArray  datagram= "five";

    if (udpSocket->writeDatagram(datagram, datagram.size(), broadcastAddress, 8000))
    {
        // 消息成功发送
        qDebug()<<"广播成功";
    } else {
        // 消息发送失败
        qDebug()<<"广播失败";
    }
}
void SetWig:: udpRecvSlot()
{
    char buf[1024]={0};
    QHostAddress sender;

    //读取数据
    udpSocket->readDatagram(buf, sizeof(buf), &sender, &senderPort);
    if(strncmp(buf,"yes",3)==0)
    {
        qDebug()<<"隶属于本机"<< endl;
        tcpip=sender.toString();

        ui->textBrowserIP->clear();
        ui->textBrowserPort->clear();

        ui->textBrowserIP->append(sender.toString());
        ui->textBrowserPort->append("8000");

    }
    else
    {
        qDebug()<<"未搜索到相关设备或未回复！"<<endl;
    }
}

void SetWig::btnConnectSolt()
{
    tcpSocket1->connectToHost(tcpip,senderPort);
    qDebug()<<"TCP第一次连接成功"<<endl;


    json["type"] = 1;
    // 创建JSON文档
    QJsonDocument jsonDoc(json);
    // 将JSON文档转换为字节数组
    QByteArray jsonData = jsonDoc.toJson();
    // 发送JSON数据
    tcpSocket1->write(jsonData);

    if(udpSocket->waitForBytesWritten(1000))
    {
        qDebug()<<"timeout"<<endl;
    }

}

void SetWig::tcpSecondConnectSlot()
{
    QString buffer = tcpSocket1->readAll();

    QString flag;
    QString text(buffer);

    QJsonDocument doc = QJsonDocument::fromJson(buffer.toUtf8());
    if (!doc.isNull() && doc.isObject())
    {
        QJsonObject obj = doc.object();
        flag = obj["flag"].toString();
    }

    if(text=="tcp1yes")
    {
        QFile readFile(Path);
        bool result=  readFile.open(QIODevice::ReadWrite);
        if(!result)
        {
            QMessageBox::warning(this,"警告","无法读取文件!!");
            return ;
        }

        QJsonObject jsonObj;
        jsonObj["type"] = 2;
        jsonObj["flag"] = "start";
        jsonObj["file_name"] = filename;
        jsonObj["file_len"] = readFile.size();
        qDebug() << readFile.size();
        QJsonDocument doc(jsonObj);
        QByteArray SendJson=doc.toJson(QJsonDocument::Indented);
        tcpSocket1->write(SendJson);
    }
    else if(text=="isliving")
    {
        qDebug()<<"TCP还在连接中"<<endl;
    }
    if (QString::compare(flag, "start") == 0)
    {
        tcpSocket2->connectToHost(tcpip,8001);
        qDebug()<<"TCP第二次连接成功"<<endl;

    }
}

void SetWig::tcpSendFileSlot()
{
    QFile readFile(Path);
    bool result=  readFile.open(QIODevice::ReadWrite);
    if(!result)
    {
        QMessageBox::warning(this,"警告","无法读取文件!!");
        return ;
    }

    QByteArray buffer;
    while(!readFile.atEnd())
    {
        buffer=readFile.read(2048);
        tcpSocket2->write(buffer);
    }

    QMessageBox::information(this,"提示信息","下发文件完成!!");

    tcpSocket2->close();

    emit disconnectTcpSignal();
}

void SetWig::timeoutHeartSlot()
{
    json["type"] = 3;
    // 创建JSON文档
    QJsonDocument jsonDoc(json);
    // 将JSON文档转换为字节数组
    QByteArray jsonData = jsonDoc.toJson();
    // 发送JSON数据
    tcpSocket1->write(jsonData);
}

void SetWig::btnpatternSlot()
{
    int id,key;
    id = ui->comboBox->currentIndex();
    //判断所选数据的key值
    if(id==0)
    {
        key=0;
    }
    else if(id==1)
    {
        key=1;

    }
    else if(id==2)
    {
        key=2;
    }
    

    QMQTT::Message message;
    // 设置主题
    message.setTopic("/app/data/down");
    QString joint=QString("{\"type\":3,\"data\":{\"type\":%1,\"period\":5}}").arg(key);
    qDebug() << "拼接为：" << joint;
    QByteArray data = joint.toUtf8();
    message.setPayload(data);
    // 发送命令
    if (GlobalVal::mqtt)
    {
        GlobalVal::mqtt->publish(message);
    }
    else
    {
        qDebug() << "MQTT client is not initialized.";
    }
}

void SetWig::disconnectedSlot()
{

    QJsonObject jsonObj;
    jsonObj["type"] = 2;
    jsonObj["flag"] = "stop";
    QJsonDocument doc(jsonObj);
    QByteArray SendJson=doc.toJson(QJsonDocument::Indented);
    tcpSocket1->write(SendJson);

}
void SetWig::openFun()
{
    pr->openfun();
}
